/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 ServerInstancesRegistry.cpp. Created on: 15.10.2009 12:04:46 
 */

#include "smartobjects/core/ServerInstancesRegistry.hpp"

namespace smartobjects {

const unsigned long ServerInstancesRegistry::DEFAULT_TIMER_WAKE_UP_INTERVAL = 30; // 30 sec

ServerInstancesRegistry::ServerInstancesRegistry() :
		m_poTimer( new cpputils::ept::Timer("SERVER_INSTANCES_REGISTRY_TIMER", false ) ),
		m_nTimerWakeUpInterval ( DEFAULT_TIMER_WAKE_UP_INTERVAL ),
		m_bHasInstancesByTime ( false) {
}

ServerInstancesRegistry::~ServerInstancesRegistry() {
	m_poTimer->cancelAll();
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxInstances);
	InstancesPerConnectionMap mTmpMap = m_mInstancesPerConnection;
	m_mInstancesPerConnection.clear();
	oLock.unlock();

	foreach(InstancesPerConnectionMap::left_map::value_type oPair, mTmpMap.left) {
		oPair.first->delConnectionListener(this);
		oPair.first->release();
	}

	oLock.lock();
	foreach(IServerSkeleton* poInstance, m_aInstances) {
		poInstance->release();
	}
	m_aInstances.clear();

	oLock.unlock();
	m_poTimer->release();
}

void ServerInstancesRegistry::addInstance ( IServerSkeleton* poInstance ) {
	LifecycleControlParams& oLtcp = poInstance->getLifecycleControlParams();
	if(!oLtcp.isDestroyByLastActivityTime() && !oLtcp.isDestroyByRemoteConnectionClosed())
		throw SmartBusSystemException ("Invalid life time control params. At least one of controls params must be selected!");

	boost::unique_lock<boost::recursive_mutex> oLock(m_mxInstances);
	m_aInstances.insert(poInstance);
	poInstance->addRef();
	oLock.unlock();

	if(oLtcp.isDestroyByLastActivityTime() && m_bHasInstancesByTime) {
		m_bHasInstancesByTime = true;
		const Timer::TimerId nTimerId = 0;
		m_poTimer->schedule(nTimerId,
				(unsigned int)m_nTimerWakeUpInterval * 1000,
				boost::bind(&ServerInstancesRegistry::onTimer, this, _1)
		);
	}
	fireOnRegister(poInstance);
}

void ServerInstancesRegistry::attachInstanceClientHandler ( ConnectionHandler* poHandler, IServerSkeleton* poInstance ) {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxInstances);
	if(m_aInstances.find(poInstance) == m_aInstances.end())
		throw SmartBusSystemException ("Unable to attache instance to connection handler. The specified instance is not found in the registry!");
	IConnection* poConnection = poHandler->getConnection();
	if(poConnection!=NULL) {
		if(m_mInstancesPerConnection.left.find(poConnection)==m_mInstancesPerConnection.left.end()) {
			poConnection->addConnectionListener(this);
			poConnection->addRef();
		}
		m_mInstancesPerConnection.right.insert(InstancesPerConnectionMap::right_value_type(
				poInstance, poConnection
		));
	}
}

void ServerInstancesRegistry::detachInstanceClientHandler ( ConnectionHandler* poHandler, IServerSkeleton* poInstance ) {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxInstances);
	if(m_aInstances.find(poInstance) == m_aInstances.end())
		throw SmartBusSystemException ("Unable to detach instance from connection handler. The specified instance is not found in the registry!");
	IConnection* poConnection = poHandler->getConnection();
	if(m_mInstancesPerConnection.left.find(poConnection)==m_mInstancesPerConnection.left.end()) {
		return;
	}
	m_mInstancesPerConnection.right.erase(poInstance);
	bool bNeedToConnectionRelease = m_mInstancesPerConnection.left.find(poConnection)==m_mInstancesPerConnection.left.end();
	oLock.unlock();

	if(bNeedToConnectionRelease) {
		poConnection->delConnectionListener(this);
		poConnection->release();
	}
}

void ServerInstancesRegistry::removeInstance ( IServerSkeleton* poInstance ) {
	typedef std::list<IConnection*> TempConnectionList;
	TempConnectionList aTempConnectionList;
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxInstances);
	InstancesSet::iterator it = m_aInstances.find(poInstance);
	if( it == m_aInstances.end())
		return;
	m_aInstances.erase(it);

	std::pair< InstancesPerConnectionMap::right_iterator, InstancesPerConnectionMap::right_iterator> itPair =
			m_mInstancesPerConnection.right.equal_range(poInstance);
	for( InstancesPerConnectionMap::right_iterator itr = itPair.first; itr!= itPair.second; itr++ ) {
		aTempConnectionList.push_back(itr->second);
	}
	m_mInstancesPerConnection.right.erase(poInstance);
	for(TempConnectionList::iterator itc = aTempConnectionList.begin(); itc!= aTempConnectionList.end();) {
		if(m_mInstancesPerConnection.left.find(*itc)!=m_mInstancesPerConnection.left.end()) {
			TempConnectionList::iterator itcN = itc;
			itcN++;
			aTempConnectionList.erase(itc);
			itc = itcN;
		}
		else
			itc++;
	}

	oLock.unlock();

	fireOnUnregister(poInstance);
	poInstance->release();


	foreach(IConnection* poConnection, aTempConnectionList) {
		poConnection->delConnectionListener(this);
		poConnection->release();
	}

}

int ServerInstancesRegistry::getInstancesCount() {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxInstances);
	return m_aInstances.size();
}

void ServerInstancesRegistry::setTimerWakeUpInterval ( unsigned long nIntervalInSec ) {
	m_nTimerWakeUpInterval = nIntervalInSec;
}

unsigned long ServerInstancesRegistry::getTimerWakeUpInterval () {
	return m_nTimerWakeUpInterval;
}

void ServerInstancesRegistry::onTimer(Timer::TimerId nTimerId) {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxInstances);
	time_t nCurrentTime = time(NULL);

	for(InstancesSet::iterator it = m_aInstances.begin(); it!= m_aInstances.end();) {
		IServerSkeleton* poInstance = *it;
		if(poInstance->getLifecycleControlParams().isDestroyByLastActivityTime()) {
			time_t nLastActivityTime = poInstance->getLastActivityTime();
			if( nCurrentTime - nLastActivityTime > (time_t) (poInstance->getLifecycleControlParams().getMaxLastActivityAwaitTime() * 1000 )) {
				InstancesSet::iterator itN = it;
				itN++;
				removeInstance(poInstance);
				it = itN;
			}
			else
				it++;
		}
	}


	if(m_aInstances.empty()) {
		m_bHasInstancesByTime = false;
		return;
	}

	oLock.unlock();
	m_poTimer->schedule(++nTimerId,
			(unsigned int)m_nTimerWakeUpInterval * 1000,
			boost::bind(&ServerInstancesRegistry::onTimer, this, _1)
	);
}

void ServerInstancesRegistry::onDisconnected(IConnection* poConnection) throw() {
	poConnection->delConnectionListener(this);

	boost::unique_lock<boost::recursive_mutex> oLock(m_mxInstances);

	std::pair<InstancesPerConnectionMap::left_iterator, InstancesPerConnectionMap::left_iterator> itPair
		= m_mInstancesPerConnection.left.equal_range(poConnection);

	for(InstancesPerConnectionMap::left_iterator it = itPair.first; it!=itPair.second; it++) {
		IServerSkeleton* poInstance = it->second;
		if(poInstance->getLifecycleControlParams().isDestroyByRemoteConnectionClosed()) {
			m_aInstances.erase( poInstance );
			fireOnUnregister(poInstance);
			poInstance->release();
		}
	}
	m_mInstancesPerConnection.left.erase(poConnection);
	oLock.unlock();

	poConnection->release();

}

void ServerInstancesRegistry::addListener ( IServerInstancesRegistryListener* poListener ) {
	boost::recursive_mutex::scoped_lock oLock ( m_mxRegistryListeners );
	if( !m_oPALRegistryListeners.isActivated() ) {
		m_aRegistryListeners.push_back(poListener);
	}
	else {
		m_oPALRegistryListeners.putListenerToAdd(poListener);
	}

}

void ServerInstancesRegistry::delListener ( IServerInstancesRegistryListener* poListener ) {
	boost::recursive_mutex::scoped_lock oLock ( m_mxRegistryListeners );
	if( !m_oPALRegistryListeners.isActivated() ) {
		m_aRegistryListeners.remove(poListener);
	}
	else {
		m_oPALRegistryListeners.putListenerToRemove(poListener);
	}
}


void ServerInstancesRegistry::processingPostActionAvailabilityListeners() {
	m_oPALRegistryListeners.deactivate();
	foreach( PostActionListenersContainer<IServerInstancesRegistryListener>::PostActionQueueItem item, m_oPALRegistryListeners.getPostActionQueue()) {
		if(item.isActionToAdd()) {
			addListener( item.getListener() );
		}
		else
		if(item.isActionToRemove()) {
			delListener( item.getListener() );
		}
	}
	m_oPALRegistryListeners.reset();
}

void ServerInstancesRegistry::fireOnRegister(IServerSkeleton* poSkeleton) {
	boost::recursive_mutex::scoped_lock oLock ( m_mxRegistryListeners );
	m_oPALRegistryListeners.activate();
	foreach(IServerInstancesRegistryListener* poListener, m_aRegistryListeners) {
		poListener->onRegisterInstance( poSkeleton );
	}
	processingPostActionAvailabilityListeners();
}

void ServerInstancesRegistry::fireOnUnregister(IServerSkeleton* poSkeleton) {
	boost::recursive_mutex::scoped_lock oLock ( m_mxRegistryListeners );
	m_oPALRegistryListeners.activate();
	foreach(IServerInstancesRegistryListener* poListener, m_aRegistryListeners) {
		poListener->onUnregisterInstance( poSkeleton );
	}
	processingPostActionAvailabilityListeners();
}

}
